package io.renren.modules.sys.controller;

import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.sys.entity.BusiBusinessEntity;
import io.renren.modules.sys.entity.BusiServiceEntity;
import io.renren.modules.sys.entity.Constant;
import io.renren.modules.sys.entity.JsonData;
import io.renren.modules.sys.entity.business.Business;
import io.renren.modules.sys.service.BusiBusinessService;
import io.renren.modules.sys.service.BusiServiceService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.Map;



/**
 * 
 * 操作订购业务类（包括订购、产品）
 * @date 2018-08-09 10:31:25
 */
@RestController
@RequestMapping("sys/busibusiness")
public class BusiBusinessController {
    @Autowired
    private BusiBusinessService busiBusinessService;

    @Autowired
    private BusiServiceService busiServiceService;

    /**
     * 获取验证码
     *
     * 需要参数：
     * 用户手机号码   userNumber
     * 提醒短信内容   orderMsg
     * 企业代码        spid
     * 产品代码（10位） serviceType
     * 操作码          operatecode
         *  * 0：代扣费
             1：定制
             2：退订
             4：点播
     * 扣费类型     feeType
                2：按条/次计费
                3：按包月收取
     * 费率       fee  (可为空)
     * 订购渠道   orderMethod (可为空)
                 02：客服电话
                 06：IVR
                 04：WEB网站
                 10：营销渠道批量操作
     */
    @ResponseBody
    @RequestMapping(value = "/verified", method = RequestMethod.POST)
    public JsonData verified(@RequestParam Map<String, String> params){
        Business business = putDataByParam(params);

        //TODO 将当前请求用户存入数据库，如果间隔小于？ 则不执行

        //需要参数
        JsonData jsonData = busiBusinessService.getVerification(business);
        //将操作记录到数据库中
        BusiBusinessEntity busi = new BusiBusinessEntity();
        busi.setMobile(business.getUserNumber());
        busi.setServiceType(business.getServiceType());
        busi.setUrl(business.getUrl());
        busi.setResult(jsonData.getMsg());
        busi.setCreateTime(new Date());
        busi.setStatus(Constant.StatusConstant.Noral);
        busi.setStartTime(new Date());
        busiBusinessService.insert(busi);

        return jsonData;
    }


    /**
     * 订购业务
     */
    @RequestMapping(value = "/order", method = RequestMethod.POST)
    public JsonData order(@RequestParam Map<String, String> params) {
        Business business = putDataByParam(params);

        JsonData jsonData = busiBusinessService.order(business);
        business = (Business) jsonData.getObj();

        //将操作记录到数据库中
        BusiBusinessEntity busi = new BusiBusinessEntity();
        busi.setMobile(business.getUserNumber());
        busi.setServiceType(business.getServiceType());
        busi.setUrl(business.getUrl());
        busi.setResult(jsonData.getMsg());
        busi.setCreateTime(new Date());
        busi.setStatus(Constant.StatusConstant.Noral);
        busi.setStartTime(new Date());
        busiBusinessService.insert(busi);
        return jsonData;
    }

    /**
     * 退订业务
     */
    @RequestMapping(value = "/cancel", method = RequestMethod.POST)
    public JsonData cancel(@RequestParam Map<String, String> params) {
        Business business = putDataByParam(params);
        //操作码改为  2   退订
        params.put("operateCode", Constant.OperateCode.Cancel);

        JsonData jsonData = busiBusinessService.order(business);

        if (jsonData.isSuccess()) {
            //将当前用户的业务状态改为取消
            BusiBusinessEntity busi = new BusiBusinessEntity();
            busi.setStartTime(new Date());
            busi.setMobile(business.getUserNumber());
            busi.setServiceType(business.getServiceType());
            busi.setStatus(Constant.StatusConstant.Cancel);
            busiBusinessService.insert(busi);
        }

        return jsonData;
    }

    /**
     * 根据产品id 获取产品信息  并放放入business对象中
     * @param params
     * @return
     */
    private Business putDataByParam(Map<String, String> params) {
        Business business = new Business();
        business.setServiceType(params.get("serviceType"));
        business.setUserNumber(params.get("userNumber"));
        String orderMethod = params.get("orderMethod");
        if (orderMethod != null) {
            business.setOrderMethod(orderMethod);
        }
        String orderCode = params.get("orderCode");
        if (StringUtils.isNotEmpty(orderCode)) {
            business.setOrderCode(orderCode);
        }

        BusiServiceEntity busi = busiServiceService.getBusiServiceByServiceType(business.getServiceType());
        business.setSpid(busi.getBusiSpid());
        business.setOperateCode(busi.getOperateCode());
        business.setFeeType(busi.getBusiFeeType());
        business.setFee(busi.getBusiFee());
        business.setOrderMethod(busi.getOrderMethod());
        return business;
    }



    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:busibusiness:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = busiBusinessService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:busibusiness:info")
    public R info(@PathVariable("id") Integer id){
        BusiBusinessEntity busiBusiness = busiBusinessService.selectById(id);

        return R.ok().put("busiBusiness", busiBusiness);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:busibusiness:save")
    public R save(@RequestBody BusiBusinessEntity busiBusiness){
        busiBusinessService.insert(busiBusiness);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:busibusiness:update")
    public R update(@RequestBody BusiBusinessEntity busiBusiness){
        ValidatorUtils.validateEntity(busiBusiness);
        busiBusinessService.updateAllColumnById(busiBusiness);//全部更新
        
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:busibusiness:delete")
    public R delete(@RequestBody Integer[] ids){
        busiBusinessService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }

}
